package com.homework.controller;

import com.homework.dto.Result;
import com.homework.entity.Admin;
import com.homework.mapper.AdminMapper;
import com.homework.util.PasswordUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

@Slf4j
@RestController
@RequestMapping("/api/debug/password")
public class PasswordResetController {

    @Autowired
    private AdminMapper adminMapper;

    /**
     * 重置admin密码为admin123
     */
    @PostMapping("/reset-admin")
    public Result<String> resetAdminPassword() {
        try {
            log.info("开始重置admin密码");

            // 查找admin用户
            Admin admin = adminMapper.selectOne(
                new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<Admin>()
                    .eq(Admin::getUsername, "admin")
            );

            if (admin == null) {
                log.warn("admin用户不存在");
                return Result.error("admin用户不存在");
            }

            // 生成新的密码哈希
            String newPassword = "admin123";
            String encodedPassword = PasswordUtil.encodePassword(newPassword);

            log.info("原始密码: {}", newPassword);
            log.info("新的密码哈希: {}", encodedPassword);
            log.info("验证新哈希: {}", PasswordUtil.matches(newPassword, encodedPassword));

            // 更新密码
            admin.setPassword(encodedPassword);
            admin.setUpdatedAt(LocalDateTime.now());
            adminMapper.updateById(admin);

            log.info("admin密码重置成功");
            return Result.success("admin密码已重置为: " + newPassword + " (哈希: " + encodedPassword + ")");

        } catch (Exception e) {
            log.error("重置admin密码失败", e);
            return Result.error("重置失败: " + e.getMessage());
        }
    }

    /**
     * 验证密码
     */
    @PostMapping("/verify")
    public Result<String> verifyPassword(@RequestParam String password, @RequestParam String hash) {
        try {
            boolean matches = PasswordUtil.matches(password, hash);
            log.info("密码验证 - 密码: [{}], 哈希: [{}], 结果: [{}]", password, hash, matches);
            return Result.success("验证结果: " + matches);
        } catch (Exception e) {
            log.error("密码验证失败", e);
            return Result.error("验证失败: " + e.getMessage());
        }
    }

    /**
     * 生成密码哈希
     */
    @GetMapping("/encode")
    public Result<String> encodePassword(@RequestParam String password) {
        try {
            String encoded = PasswordUtil.encodePassword(password);
            log.info("生成密码哈希 - 密码: [{}], 哈希: [{}]", password, encoded);
            return Result.success(encoded);
        } catch (Exception e) {
            log.error("生成密码哈希失败", e);
            return Result.error("生成失败: " + e.getMessage());
        }
    }
}